package com.jh.fcsm.common;


import com.sun.org.apache.bcel.internal.generic.RETURN;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.io.File;
import java.io.FilenameFilter;
public  class JarHashCalculator {


    /**
     *  方法描述:获取JAR MD5哈希值
     *  @author ZCM
     *  * @date:2024年03月03日
     * */
    public static String calculateHash() throws IOException, NoSuchAlgorithmException {
        // 获取当前 JAR 文件的路径
        String jarPath = JarHashCalculator.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        int index=jarPath.indexOf("/");
        String resultPath=jarPath.substring(index+1,jarPath.length());
        String toRemove="jar";
        String loationPath = resultPath.split(toRemove)[0]+"jar";
        File jarFile = new File(loationPath);
        MessageDigest md = MessageDigest.getInstance("MD5");

        try(FileInputStream fis = new FileInputStream(jarFile)) {
            byte[] buffer = new byte[1024];
            int numRead;
            while ((numRead = fis.read(buffer)) != -1) {
                md.update(buffer, 0, numRead);
            }
        }
        byte[] digest = md.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
        }
        return  sb.toString();
    }

    /**
     *  方法描述: 遍历获取JAR 文件旅游局
     *  @author ZCM
     *  * @date:2024年03月03日
     * */
    public static String findJarFiles(File dir) {
        String path=null;
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    findJarFiles(file);
                } else {
                    String fileName = file.getName().toLowerCase();
                    if (fileName.endsWith(".jar")) {
                        path=file.getAbsolutePath();
                    }
                }
            }
        }
      return  path;
    }

    /**
     *  方法描述: 去除字符串前后斜杠
     *  @author ZCM
     *  * @date:2024年03月03日
     * */
    public static String removeSlashes(String str) {
        while (str.startsWith("/")) {
            str = str.substring(1);
        }
        while (str.endsWith("/")) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

}
